package com.zhitong.money.controller;

import com.github.pagehelper.PageInfo;
import com.zhitong.money.entity.AjaxResponse;
import com.zhitong.money.entity.Menu;
import com.zhitong.money.services.api.IMenuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin
@Slf4j
@RestController
public class MenuContro {

    @Autowired
    private IMenuService service;

    @GetMapping("/menus")
    public AjaxResponse getAllMenu() throws Exception{
        List<Menu> allMenu = service.findAllMenu();
        return AjaxResponse.success(allMenu);
    }

    @GetMapping("/menu/{id}")
    public AjaxResponse getMenuById(@PathVariable String id) throws Exception{
        Menu menuById = service.findMenuById(id);
        return AjaxResponse.success(menuById);
    }

    @PostMapping("/menus")
    public AjaxResponse getMenuByPage(@RequestBody Map<String,Object> map) throws Exception{
        PageInfo menuByMap = service.findMenuByPage(map);
        return AjaxResponse.success(menuByMap);
    }

    @PostMapping("/menuMap")
    public AjaxResponse getMenuByMap(@RequestBody Map<String,Object> map) throws Exception{
        List<Menu> menuByMap = service.findMenuByMap(map);
        return AjaxResponse.success(menuByMap);
    }

    @RequiresPermissions({"addMenu"})
    @PostMapping("/menu")
    public AjaxResponse addMenu(@RequestBody Menu menu) throws Exception{
        service.addMenu(menu);
        return AjaxResponse.success("添加菜单成功!");
    }

    @RequiresPermissions({"updateMenu"})
    @PutMapping("/menu")
    public AjaxResponse updateMenu(@RequestBody Menu menu) throws Exception{
        service.updateMenu(menu);
        return AjaxResponse.success("更新菜单成功!");
    }

    @RequiresPermissions({"delMenu"})
    @DeleteMapping("/menu/{id}")
    public AjaxResponse delMenu(@PathVariable("id")String id) throws Exception{
        int i = service.delMenu(id);
        if (i>0){
            return AjaxResponse.success("删除菜单成功!");
        }
        return AjaxResponse.fail("删除菜单失败!菜单被关联");

    }

    @RequiresPermissions({"delMenu"})
    @PostMapping("/delMenus")
    public AjaxResponse delMenus(@RequestBody List<String> ids) throws Exception{
        int i = service.delMenuByIds(ids);
        if (i>0){
            return AjaxResponse.success("删除菜单成功!");
        }
        return AjaxResponse.fail("删除菜单失败!菜单被关联");
    }

}
